import {
    createRouter,
    RouteRecordRaw,
    createWebHistory,
    createWebHashHistory
} from 'vue-router';

import type { App } from 'vue';
import { useAdminStoreWithOut } from '../store/modules/admin'
import { umsAdmin } from '../request/http'

const adminStore = useAdminStoreWithOut();
const routes: RouteRecordRaw[] = [
    {
        path: '/login',
        name: 'login',
        component:() =>import('../views/login/index.vue')
    },
];

const router = createRouter({
    history: createWebHashHistory(),
    routes
});

// 前置导航守卫
router.beforeEach(async (to, from, next) => {
    
    const token = localStorage.getItem('token');
    // 当token存在并且menus数组的长度为空时发起请求
    // console.log(useAdminStoreWithOut.length);
    if (token && adminStore.menus.length === 0) {
        const adminData = await umsAdmin.getAdminInfo();
        if (adminData.code === 200) {
            adminStore.updateMenus(adminData.data.menus);
            // 动态生成路由规则
            const newMenus = adminStore.genNewMenus;
            for (let key in newMenus) {
                let meunObj: RouteRecordRaw = {
                    path: '/' + newMenus[key].name,
                    name: newMenus[key].name,
                    component: () => import('../views/home/index.vue'),
                    children:[]
                }
                newMenus[key].children.forEach((item) => {
                    meunObj.children?.push ({
                        path: item.name,
                        name: item.name,
                        component:()=> import('../views/'+newMenus[key].name+'/'+item.name                 +'/index.vue')
                        // component:()=>import(`../views/${newMenus[key].name}/${item.name}/index.vue`)
                    })
                })
                // 添加到路由里面
                router.addRoute(meunObj)
            }
            router.addRoute({
                path: '/',
                name: 'home',
                component: () => import('../views/home/index.vue'),
                children: [
                    {
                        path: 'index',
                        name: 'index',
                        component:()=>import('../views/index/index.vue')
                    }
                ]
            })
            return next(to); 
        } else {
            // 删掉token，重定向到login
            localStorage.clear();
            return next('./login');
        }
    } else if (token && to.path === '/login') {
        return next(from)
    } else if (!token && to.path !== '/login') {
        return next('/login')
    } else {
        next();
    }
    
})

export function initRouter(app: App<Element>) {
    app.use(router)
};

